// 简化版学生管理系统前端应用

// API接口
const API_BASE_URL = 'http://localhost:8080';

// API函数
const api = {
  async getAllStudents() {
    const response = await fetch(`${API_BASE_URL}/api/students`);
    if (!response.ok) throw new Error('获取学生列表失败');
    return response.json();
  },

  async getStudentById(id) {
    const response = await fetch(`${API_BASE_URL}/api/students/${id}`);
    if (!response.ok) throw new Error('获取学生信息失败');
    return response.json();
  },

  async searchStudents(keyword) {
    const response = await fetch(`${API_BASE_URL}/api/students?keyword=${encodeURIComponent(keyword)}`);
    if (!response.ok) throw new Error('搜索学生失败');
    return response.json();
  },

  async createStudent(studentData) {
    const response = await fetch(`${API_BASE_URL}/api/students`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(studentData),
    });
    if (!response.ok) throw new Error('创建学生失败');
    return response.json();
  },

  async updateStudent(id, studentData) {
    const response = await fetch(`${API_BASE_URL}/api/students/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(studentData),
    });
    if (!response.ok) throw new Error('更新学生失败');
    return response.json();
  },

  async deleteStudent(id) {
    const response = await fetch(`${API_BASE_URL}/api/students/${id}`, { method: 'DELETE' });
    if (!response.ok) throw new Error('删除学生失败');
    return true;
  },

  async getStatistics() {
    const response = await fetch(`${API_BASE_URL}/api/students/statistics`);
    if (!response.ok) throw new Error('获取统计信息失败');
    return response.json();
  }
};

// 全局状态
let currentTab = 'students';
let students = [];
let statistics = null;

// DOM元素
const loadingEl = document.getElementById('loading');
const errorEl = document.getElementById('error');
const successEl = document.getElementById('success');
const contentEl = document.getElementById('content');
const modalEl = document.getElementById('modal');

// 工具函数
function showLoading() {
  loadingEl.style.display = 'block';
  errorEl.style.display = 'none';
  successEl.style.display = 'none';
  contentEl.innerHTML = '';
}

function hideLoading() {
  loadingEl.style.display = 'none';
}

function showError(message) {
  errorEl.textContent = message;
  errorEl.style.display = 'block';
  hideLoading();
}

function showSuccess(message) {
  successEl.textContent = message;
  successEl.style.display = 'block';
  setTimeout(() => {
    successEl.style.display = 'none';
  }, 3000);
}

function formatDate(dateString) {
  return new Date(dateString).toLocaleDateString('zh-CN');
}

// 导航功能
document.querySelectorAll('.nav-tab').forEach(tab => {
  tab.addEventListener('click', () => {
    const tabName = tab.dataset.tab;
    switchTab(tabName);
  });
});

function switchTab(tabName) {
  currentTab = tabName;
  
  // 更新导航样式
  document.querySelectorAll('.nav-tab').forEach(tab => {
    tab.classList.remove('active');
  });
  document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
  
  // 加载对应内容
  switch (tabName) {
    case 'students':
      loadStudentsTab();
      break;
    case 'statistics':
      loadStatisticsTab();
      break;
    case 'add':
      loadAddStudentTab();
      break;
  }
}

// 学生列表功能
async function loadStudentsTab() {
  showLoading();
  try {
    students = await api.getAllStudents();
    renderStudentsList();
    hideLoading();
  } catch (error) {
    showError('加载学生列表失败: ' + error.message);
  }
}

function renderStudentsList() {
  const html = `
    <div style="margin-bottom: 20px;">
      <div class="search-box">
        <input type="text" id="searchInput" placeholder="搜索学生姓名、学号或专业...">
        <button class="btn btn-primary" onclick="searchStudents()">搜索</button>
        <button class="btn btn-secondary" onclick="loadStudentsTab()">刷新</button>
      </div>
    </div>
    
    <div style="overflow-x: auto;">
      <table class="table">
        <thead>
          <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
            <th>专业</th>
            <th>GPA</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          ${students.map(student => `
            <tr>
              <td>${student.studentId}</td>
              <td>${student.name}</td>
              <td>${student.age}</td>
              <td>${student.gender}</td>
              <td>${student.major}</td>
              <td>${student.gpa}</td>
              <td>
                <button class="btn btn-secondary" onclick="editStudent(${student.id})" style="margin-right: 5px;">编辑</button>
                <button class="btn btn-danger" onclick="deleteStudent(${student.id})">删除</button>
              </td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
    
    ${students.length === 0 ? '<p style="text-align: center; color: #666; margin-top: 20px;">暂无学生数据</p>' : ''}
  `;
  
  contentEl.innerHTML = html;
}

async function searchStudents() {
  const keyword = document.getElementById('searchInput').value.trim();
  if (!keyword) {
    loadStudentsTab();
    return;
  }
  
  showLoading();
  try {
    students = await api.searchStudents(keyword);
    renderStudentsList();
    hideLoading();
  } catch (error) {
    showError('搜索失败: ' + error.message);
  }
}

async function deleteStudent(id) {
  if (!confirm('确定要删除这个学生吗？')) return;
  
  try {
    await api.deleteStudent(id);
    showSuccess('学生删除成功');
    loadStudentsTab();
  } catch (error) {
    showError('删除失败: ' + error.message);
  }
}

function editStudent(id) {
  const student = students.find(s => s.id === id);
  if (!student) return;
  
  showEditModal(student);
}

// 统计信息功能
async function loadStatisticsTab() {
  showLoading();
  try {
    statistics = await api.getStatistics();
    renderStatistics();
    hideLoading();
  } catch (error) {
    showError('加载统计信息失败: ' + error.message);
  }
}

function renderStatistics() {
  const html = `
    <h2>📊 统计信息</h2>
    
    <div class="stats-grid">
      <div class="stat-card">
        <h3>${statistics.totalStudents}</h3>
        <p>总学生数</p>
      </div>
      <div class="stat-card">
        <h3>${statistics.averageGpa.toFixed(2)}</h3>
        <p>平均GPA</p>
      </div>
      <div class="stat-card">
        <h3>${statistics.maleCount}</h3>
        <p>男生人数</p>
      </div>
      <div class="stat-card">
        <h3>${statistics.femaleCount}</h3>
        <p>女生人数</p>
      </div>
    </div>
    
    <div style="margin-top: 30px;">
      <h3>专业分布</h3>
      <table class="table">
        <thead>
          <tr>
            <th>专业</th>
            <th>学生人数</th>
            <th>平均GPA</th>
          </tr>
        </thead>
        <tbody>
          ${Object.entries(statistics.majorStats).map(([major, data]) => `
            <tr>
              <td>${major}</td>
              <td>${data.count}</td>
              <td>${data.averageGpa.toFixed(2)}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
    
    <div style="margin-top: 30px;">
      <h3>GPA排名前十</h3>
      <table class="table">
        <thead>
          <tr>
            <th>排名</th>
            <th>学号</th>
            <th>姓名</th>
            <th>专业</th>
            <th>GPA</th>
          </tr>
        </thead>
        <tbody>
          ${statistics.top10Students.map((student, index) => `
            <tr>
              <td>${index + 1}</td>
              <td>${student.studentId}</td>
              <td>${student.name}</td>
              <td>${student.major}</td>
              <td>${student.gpa}</td>
            </tr>
          `).join('')}
        </tbody>
      </table>
    </div>
  `;
  
  contentEl.innerHTML = html;
}

// 添加学生功能
function loadAddStudentTab() {
  const html = `
    <h2>➕ 添加学生</h2>
    <form id="addStudentForm" style="max-width: 500px;">
      <div class="form-group">
        <label for="studentId">学号 *</label>
        <input type="text" id="studentId" name="studentId" required>
      </div>
      
      <div class="form-group">
        <label for="name">姓名 *</label>
        <input type="text" id="name" name="name" required>
      </div>
      
      <div class="form-group">
        <label for="age">年龄 *</label>
        <input type="number" id="age" name="age" min="16" max="30" required>
      </div>
      
      <div class="form-group">
        <label for="gender">性别 *</label>
        <select id="gender" name="gender" required>
          <option value="">请选择</option>
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </div>
      
      <div class="form-group">
        <label for="major">专业 *</label>
        <input type="text" id="major" name="major" required>
      </div>
      
      <div class="form-group">
        <label for="gpa">GPA *</label>
        <input type="number" id="gpa" name="gpa" min="0" max="4" step="0.01" required>
      </div>
      
      <button type="submit" class="btn btn-primary">添加学生</button>
      <button type="button" class="btn btn-secondary" onclick="switchTab('students')" style="margin-left: 10px;">返回列表</button>
    </form>
  `;
  
  contentEl.innerHTML = html;
  
  // 绑定表单提交事件
  document.getElementById('addStudentForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    await addStudent();
  });
}

async function addStudent() {
  const formData = new FormData(document.getElementById('addStudentForm'));
  const studentData = {
    studentId: formData.get('studentId'),
    name: formData.get('name'),
    age: parseInt(formData.get('age')),
    gender: formData.get('gender'),
    major: formData.get('major'),
    gpa: parseFloat(formData.get('gpa'))
  };
  
  try {
    await api.createStudent(studentData);
    showSuccess('学生添加成功');
    document.getElementById('addStudentForm').reset();
    switchTab('students');
  } catch (error) {
    showError('添加失败: ' + error.message);
  }
}

// 模态框功能
function showEditModal(student) {
  document.getElementById('modal-title').textContent = '编辑学生';
  document.getElementById('modal-body').innerHTML = `
    <form id="editStudentForm">
      <input type="hidden" id="editId" value="${student.id}">
      
      <div class="form-group">
        <label for="editStudentId">学号 *</label>
        <input type="text" id="editStudentId" value="${student.studentId}" required>
      </div>
      
      <div class="form-group">
        <label for="editName">姓名 *</label>
        <input type="text" id="editName" value="${student.name}" required>
      </div>
      
      <div class="form-group">
        <label for="editAge">年龄 *</label>
        <input type="number" id="editAge" value="${student.age}" min="16" max="30" required>
      </div>
      
      <div class="form-group">
        <label for="editGender">性别 *</label>
        <select id="editGender" required>
          <option value="男" ${student.gender === '男' ? 'selected' : ''}>男</option>
          <option value="女" ${student.gender === '女' ? 'selected' : ''}>女</option>
        </select>
      </div>
      
      <div class="form-group">
        <label for="editMajor">专业 *</label>
        <input type="text" id="editMajor" value="${student.major}" required>
      </div>
      
      <div class="form-group">
        <label for="editGpa">GPA *</label>
        <input type="number" id="editGpa" value="${student.gpa}" min="0" max="4" step="0.01" required>
      </div>
      
      <button type="submit" class="btn btn-primary">保存修改</button>
      <button type="button" class="btn btn-secondary" onclick="closeModal()" style="margin-left: 10px;">取消</button>
    </form>
  `;
  
  modalEl.classList.add('show');
  
  // 绑定表单提交事件
  document.getElementById('editStudentForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    await updateStudent();
  });
}

function closeModal() {
  modalEl.classList.remove('show');
}

async function updateStudent() {
  const id = document.getElementById('editId').value;
  const studentData = {
    studentId: document.getElementById('editStudentId').value,
    name: document.getElementById('editName').value,
    age: parseInt(document.getElementById('editAge').value),
    gender: document.getElementById('editGender').value,
    major: document.getElementById('editMajor').value,
    gpa: parseFloat(document.getElementById('editGpa').value)
  };
  
  try {
    await api.updateStudent(id, studentData);
    showSuccess('学生信息更新成功');
    closeModal();
    loadStudentsTab();
  } catch (error) {
    showError('更新失败: ' + error.message);
  }
}

// 点击模态框外部关闭
modalEl.addEventListener('click', (e) => {
  if (e.target === modalEl) {
    closeModal();
  }
});

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
  switchTab('students');
});